#include "stdafx.h"
#include "WCTransaction.h"
#include "WCUtility.h"


WCTransaction::WCTransaction(int port):WCPeer(port)
{
	
}
WCTransaction::~WCTransaction()
{
	
}
void WCTransaction::start()
{
	run();
}
void WCTransaction::run()
{
	//create thread to receive
	CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)recvProcess, this, 0, NULL);
	printf("connect to (ip + port):\n");
	char ip[12];
	int port;
	char buf[MAX_BUFFER_SIZE];
	scanf("%s%d", ip, &port);
	while(true)
	{
		printf("input message:");
		WCMessage message;
		scanf("%s", message.content);
		message.type = W_MS_MSG;
		memcpy(buf, &message, sizeof(message));
		send(ip, port, buf, sizeof(buf));
	}
}

unsigned long _stdcall recvProcess(LPVOID pParam)
{
	WCTransaction* pTrans = (WCTransaction*) pParam;
	char ip[12];
	int port;
	char buf[MAX_BUFFER_SIZE];
	while(true)
	{
		pTrans->receive(ip, &port, buf, sizeof(buf));
		WCMessage message;
		memcpy(&message, buf, sizeof(message));
		if(message.type == W_MS_MSG)
			printf("\nReceived datagram from %s:%d--%s", ip, port, message.content);
		else
			printf("\nReceived datagram from %s:%d--unknown type", ip, port);
	}
}